define(['app'], function(app) {
    app.controller('editModule', function($http, $uibModalInstance, toastr, _context, _dialog) {
        var self = this;
        self.origin = '';
        self.module = '';
        self.action = '';

        self.init = function() {
            // _context = {module}
            self.origin = _context.module;
            self.module = _context.module;
            self.action = (_context.module ? 'rename' : 'new');
        }

        self.save = function(valid) {
            if (valid) {
                if (_context.module) {
                    $http.put('/note/module/rename', {
                        oldModule: self.origin,
                        newModule: self.module
                    }).then(function(response) {
                        setTimeout(function() {
                            if (response.data == 'required') {
                                _dialog.alert('提示信息', '模块【' + self.origin + '】不存在！');
                            }if (response.data) {
                                toastr.success('模块【' + self.origin + '】已修改！');
                                $uibModalInstance.close(self.module);
                            } else if (response.status == 200) {
                                _dialog.alert('提示信息', '您重命名的模块已存在！');
                            }
                        }, 500);
                    });
                } else {
                    $http.put('/note/module/save', {
                        module: self.module
                    }).then(function(response) {
                        setTimeout(function() {
                            if (response.data) {
                                toastr.success('模块【' + self.module + '】已添加！');
                                $uibModalInstance.close(self.module);
                            } else if (response.status == 200) {
                                _dialog.alert('提示信息', '您新建的模块已存在！');
                            }
                        }, 500);
                    });
                }
            }
        }

        self.cancel = function() {
            $uibModalInstance.dismiss();
        }
    });
});
